package com.airticketbooking.service.serviceImpl;

import com.airticketbooking.common.utils.UserContext;
import com.airticketbooking.mapper.*;
import com.airticketbooking.po.DiscountType;
import com.airticketbooking.po.Member;
import com.airticketbooking.po.Point;
import com.airticketbooking.po.Ticket;
import com.airticketbooking.service.DiscountTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author Mr.J
 * @version 1.0.0
 * @date 2024/11/13
 * @desc
 */
@Service
@RequiredArgsConstructor

public class DiscountTypeServiceImpl implements DiscountTypeService {

	private final DiscountTypeMapper discountTypeMapper;

	private final MemberMapper memberMapper;

	private final PointMapper pointMapper;

	private final TicketMapper ticketMapper;


	private final OrderWithTicketMapper orderWithTicketMapper;


	@Override
	@Transactional
	public DiscountType getByPoint(Integer orderId) {

		Member member = memberMapper.getByUserId(UserContext.getUser().intValue());


		if (member == null) {
			throw new RuntimeException("您还不是会员,不能使用积分折扣,请先注册成为会员");
		}

//		查询用户已有积分
		Point point = pointMapper.getPointByMemberId(member.getMemberId());

//		根据用户已有积分以及本次购票将要获得积分，计算积分，得出折扣类型
		List<Integer> ticketIds = orderWithTicketMapper.getTicketIdsByOrderId(orderId);

//		计算总价
		BigDecimal totalPriceWithOrder = new BigDecimal(0);
		for (Integer ticketId : ticketIds) {
			Ticket ticket = ticketMapper.getTicketById(ticketId);
			totalPriceWithOrder = totalPriceWithOrder.add(ticket.getPrice());
		}

//		计算此次积分
		Integer newPoint = calculatePoint(totalPriceWithOrder);

//		计算总积分
		Integer newPointAndTotalPoint = point.getTotalPoints() + newPoint;


		return discountTypeMapper.getByPoint(newPointAndTotalPoint);
	}


	//	积分计算函数
	public Integer calculatePoint(BigDecimal totalPrice) {
		Integer culculatePoint = totalPrice.intValue() / 100;

		return culculatePoint;

	}


}
